package com.example.service.impl;


import com.example.dao.GoodsMapper;
import com.example.entity.Goods;
import com.example.service.GoodsService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

@Service
public class GoodsServiceImpl implements GoodsService {
    @Resource
    GoodsMapper goodsMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public PageInfo<Goods> queryAll(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        ArrayList<Goods> goodsList = goodsMapper.queryAll();
        PageInfo<Goods> pageInfo = new PageInfo<>(goodsList);
        return pageInfo;
    }
//    @CacheEvict(cacheNames = "goods")
    @Override
    public int deleteById(Integer id) {
        int count = goodsMapper.deleteById(id);
        redisTemplate.delete("goods_"+id);
        return count;

//        return goodsMapper.deleteById(id);
    }

//    @Cacheable(cacheNames = "goods",unless = "#result==null", key = "#id")
    @Override
    public Goods findById(Integer id) {
        boolean flag = redisTemplate.hasKey("goods_"+id);
        if(flag) {
            Object obj = redisTemplate.opsForValue().get("goods_" + id);
            if (obj != null) {
                return (Goods) obj;
            }
    }
        Goods goods = goodsMapper.findById(id);
        redisTemplate.opsForValue().set("goods_"+id,goods,1, TimeUnit.HOURS);
        return goods;
    }

//    @CachePut(cacheNames = "goods")
    @Override
    public int update(Goods goods) {
        int count = goodsMapper.update(goods);
        redisTemplate.opsForValue().set("goods_"+goods.getGdid(),goods);
        return count;
    }

//    @CachePut(cacheNames = "goods")
    @Override
    public int insert(Goods goods) {
        return goodsMapper.insert(goods);
    }

}





